import * as vscode from 'vscode';
import * as path from 'path';
import { calculateLevel } from './levelCalculator';

/**
 * 程序员伙伴类，实现右下角状态栏显示和互动功能
 */
export class Pet {
    // 程序员等级
    private level: number = 1;
    // 当前经验值(基于编码时长)
    private exp: number = 0;
    // 当前宠物类型
    public petType: 'cat'|'dog'|'dino' = 'cat';
    // 当前情绪状态
    private mood: string = 'happy';
    // 所有可能的情绪状态
    private moods = ['happy', 'hungry', 'angry'];
    // 状态栏项引用
    private statusBarItem: vscode.StatusBarItem;
    // 插件上下文
    private context: vscode.ExtensionContext;
    // 最后活动时间戳
    private lastActiveTime: number = Date.now();

    // 状态对象类型
    private state: {
        level: number;
        exp: number;
        mood: string;
        petType: 'cat'|'dog'|'dino';
    };

    constructor(context: vscode.ExtensionContext) {
        this.context = context;
        
        // 从持久化存储恢复状态
        const savedState = context.globalState.get<typeof this.state>('petState');
        this.state = savedState || {
            level: 1,
            exp: 0,
            mood: 'happy',
            petType: 'cat'
        };
        
        // 同步到实例属性
        this.level = this.state.level;
        this.exp = this.state.exp;
        this.mood = this.state.mood;
        this.petType = this.state.petType;

        this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
        this.updateStatus();
        this.statusBarItem.tooltip = 'Hover to select pet, click to interact';
        this.statusBarItem.command = 'code-pal.petInteract';
        
        // 显示状态栏
        this.statusBarItem.show();
    }

    /**
     * 保存当前状态到持久化存储
     */
    public saveState() {
        // 更新状态对象
        this.state = {
            level: this.level,
            exp: this.exp, 
            mood: this.mood,
            petType: this.petType
        };
        // 保存到持久化存储
        this.context.globalState.update('petState', this.state);
    }

    /**
     * 切换宠物类型
     */
    public switchPetType() {
        const types: Array<'cat'|'dog'|'dino'> = ['cat', 'dog', 'dino'];
        const currentIndex = types.indexOf(this.petType);
        this.petType = types[(currentIndex + 1) % types.length];
        this.updateStatus();
        this.saveState();
        vscode.window.showInformationMessage(`已切换为${this.petType === 'cat' ? '猫咪' : this.petType === 'dog' ? '狗狗' : '恐龙'}伙伴`);
    }

    /**
     * 更新编码时长经验值
     * @param activeTime 本次编码时长(分钟)
     */
    public updateCodingTime(activeTime: number) {
        // 确保经验值至少增加1
        const expGain = Math.max(1, Math.floor(Math.pow(activeTime, 1.5)));
        this.exp += expGain;
        
        // 确保等级不会下降
        const { level, exp } = calculateLevel(this.exp);
        this.level = Math.max(this.level, level); // 取当前等级和新等级的最大值
        this.exp = exp;
        this.updateStatus();
        this.saveState();
    }


    /**
     * 更新状态栏显示
     */
    public updateStatus() {
        // 宠物类型图标
        const petEmojis: Record<'cat'|'dog'|'dino', string> = {
            cat: '🐱',
            dog: '🐶',
            dino: '🦖'
        };

        // 确保petType有默认值
        if (!this.petType) {
            this.petType = 'cat';
        }

        // 荣誉称号配置
        const titles = [
            { min: 1, max: 5, title: '萌新', color: '#A5D6A7' },
            { min: 6, max: 10, title: '码农', color: '#81D4FA' },
            { min: 11, max: 15, title: '工程师', color: '#CE93D8' },
            { min: 16, max: 20, title: '架构师', color: '#FFAB91' },
            { min: 21, max: 25, title: '专家', color: '#FFF59D' },
            { min: 26, max: Infinity, title: '荣耀', color: '#FFCC80' }
        ];

        // 匹配当前等级称号
        const currentTitle = titles.find(t => this.level >= t.min && this.level <= t.max) || titles[0];
        
        // 等级显示文本
        const levelText = this.level <= 25 ? `Lv.${this.level}` : `G.${this.level - 25}`;
        
        // 设置状态栏
        this.statusBarItem.text = `${petEmojis[this.petType]} ${currentTitle.title} ${levelText}`;
        this.statusBarItem.color = currentTitle.color;
    }

    /**
     * 显示宠物选择菜单
     */
    public async showPetSelection() {
        interface MenuOption extends vscode.QuickPickItem {
            action: 'select-pet' | 'repo-info' | 'support-author';
            type?: 'cat' | 'dog' | 'dino';
        }

        const options: MenuOption[] = [
            { 
                label: '🐱 猫咪', 
                description: '选择猫咪作为编程伙伴', 
                action: 'select-pet',
                type: 'cat' 
            },
            { 
                label: '🐶 狗狗', 
                description: '选择狗狗作为编程伙伴', 
                action: 'select-pet',
                type: 'dog' 
            },
            { 
                label: '🦖 恐龙', 
                description: '选择恐龙作为编程伙伴', 
                action: 'select-pet',
                type: 'dino' 
            },
            { 
                label: '📦 代码仓库', 
                description: '查看项目代码仓库信息',
                action: 'repo-info'
            },
            { 
                label: '❤️ 支持作者', 
                description: '支持开发者继续维护项目',
                action: 'support-author'
            }
        ];

        const selection = await vscode.window.showQuickPick(options, {
            placeHolder: 'Code Pal 功能菜单'
        });

        if (selection) {
            switch(selection.action) {
                case 'select-pet':
                    if (selection.type) {
                        this.petType = selection.type;
                        this.updateStatus();
                        this.saveState();
                        vscode.window.showInformationMessage(
                            `已切换为${selection.type === 'cat' ? '猫咪' : selection.type === 'dog' ? '狗狗' : '恐龙'}伙伴`
                        );
                    }
                    break;
                case 'repo-info':
                    vscode.env.openExternal(vscode.Uri.parse('https://gitee.com/gao_yunji'));
                    break;
                case 'support-author':
                    const paymentImagePath = path.join(this.context.extensionPath, 'assets', 'zfb.jpg');
                    vscode.window.showInformationMessage('感谢您的支持！', {modal: true})
                        .then(() => {
                            vscode.env.openExternal(vscode.Uri.file(paymentImagePath));
                        });
                    break;
            }
        }
    }


    dispose() {
        this.statusBarItem.dispose();
    }
}
